use axum_app_common::model::PageResult;
use axum_app_macro::QueryPageBuilder;
use sea_orm::{
    sea_query::{Expr, IntoCondition, SimpleExpr},
    Condition, ConnectionTrait, DbBackend, DbConn, DbErr, EntityTrait, FromQueryResult,
    PaginatorTrait, QueryFilter, QuerySelect, Statement,
};
use tracing::error;

use crate::entity::{prelude::*, sys_user::*};

/**
 * 分页查询条件
 */
impl UserQueryCondition {
    pub fn deleted(mut self, deleted: bool) -> Self {
        if deleted {
            self.filter = self.filter.add(Column::DeleteFlag.lt(0));
        } else {
            self.filter = self.filter.add(Column::DeleteFlag.eq(0));
        }
        self
    }

    pub fn display_name_left_like(mut self, name: Option<&str>) -> Self {
        self.filter = self.filter.add_option(
            name.filter(|s| s.trim().len() > 0)
                .map(|s| Expr::col(Column::DisplayName).like(format!("{}%", s))),
        );
        self
    }

    pub fn username_eq(mut self, username: Option<&str>) -> Self {
        self.filter = self.filter.add_option(
            username
                .filter(|s| s.trim().len() > 0)
                .map(|s| Expr::col(Column::Username).eq(s)),
        );
        self
    }

    pub fn condition(self) -> Condition {
        self.filter
    }
}

#[derive(Debug, QueryPageBuilder)]
pub struct UserQuery;

impl UserQuery {
    pub async fn find_user_by_id(db: &DbConn, id: u64) -> Result<Option<Model>, DbErr> {
        SysUserEntity::find_by_id(id as i64).one(db).await
    }

    pub async fn find_user_by_userid<C>(db: &C, userid: &str) -> anyhow::Result<Option<Model>>
    where
        C: ConnectionTrait,
    {
        let res = Entity::find()
            .filter(Expr::col(Column::Userid).eq(userid).into_condition())
            .one(db)
            .await?;

        Ok(res)
    }

    //     pub async fn query_pages(
    //         db: &DbConn,
    //         page_num: u64,
    //         page_size: u64,
    //         params: UserQueryCondition,
    //     ) -> PageResult<Model> {
    //         let query = SysUserEntity::find()
    //             // 检索条件
    //             .filter(params.condition())
    //             .paginate(db, page_size);

    //         let items = query.fetch_page(page_num - 1).await;
    //         let total = query.num_items().await;

    //         let mut items = match items {
    //             Err(err) => {
    //                 error!("query_pages error: {}", err);
    //                 Vec::new()
    //             }
    //             Ok(items) => items,
    //         };
    //         items
    //             .iter_mut()
    //             .for_each(|it| it.password = String::default());

    //         let page = PageResult::<Model> {
    //             page_num,
    //             page_size,
    //             total: total.unwrap_or(0u64),
    //             items,
    //         };

    //         page
    //     }
}

pub async fn insert_user<C>(db: &C, user: ActiveModel) -> anyhow::Result<u64>
where
    C: ConnectionTrait,
{
    let res = Entity::insert(user).exec(db).await?;
    Ok(res.last_insert_id as u64)
}

pub async fn find_user_by_username<C>(db: &C, username: &str) -> anyhow::Result<Option<Model>>
where
    C: ConnectionTrait,
{
    let res = Entity::find()
        .filter(Expr::col(Column::Username).eq(username).into_condition())
        .one(db)
        .await?;

    Ok(res)
}



pub async fn find_user_by_userid<C>(db: &C, userid: &str) -> anyhow::Result<Option<Model>>
where
    C: ConnectionTrait,
{
    let res = Entity::find()
        .filter(Expr::col(Column::Userid).eq(userid).into_condition())
        .one(db)
        .await?;

    Ok(res)
}